package service

import (
	"bytes"
	"encoding/json"
	"inventory/pkg/network"
	"io"
	"io/ioutil"
	"net/http"
)

func saveBodyToHeader(r *http.Request) {
	// 需要原始body，用于签名检查
	var buf bytes.Buffer
	tee := io.TeeReader(r.Body, &buf)
	body, _ := ioutil.ReadAll(tee)
	r.Body = ioutil.NopCloser(&buf)
	r.Header.Set(network.RpcRawBodyHeader, string(body))
}

// CityExpressRegion represents CityExpressRegion.
type CityExpressRegion struct {
	StartingFee float64         `json:"starting_fee"`
	ShippingFee float64         `json:"shipping_fee"`
	Coordinates json.RawMessage `json:"coordinates"`
	CityCode    uint32          `json:"city_code" binding:"required"`
}

// EditWarehouseCityExpressRegionsRequest represents edit city express regions request.
type EditWarehouseCityExpressRegionsRequest struct {
	PStoreId uint32               `json:"p_store_id"`
	Id       uint32               `json:"id" binding:"required"`
	Regions  []*CityExpressRegion `json:"regions"`
}

//// 需要将body中特殊格式的coordinates进行格式转换，以防止http=>grpc decode失败
//// 目前coordinates在pb中之所以用string不用bytes,是为了日志打印清晰，防止bytes触发的乱码字符串污染日志
//func resetEditCityExpressPlatformRequestBody(r *http.Request) {
//	var buf bytes.Buffer
//	tee := io.TeeReader(r.Body, &buf)
//	body, _ := ioutil.ReadAll(tee)
//	req := &EditWarehouseCityExpressRegionsRequest{}
//	if err := json.Unmarshal(body, req); err != nil {
//		// 格式转换错误则放弃，由CustomProtoErrorHandler处理返回值
//		// 重置请求body
//		r.Body = ioutil.NopCloser(&buf)
//		return
//	}
//	targetReq := inventory.EditWarehouseCityExpressRegionsRequest{
//		TokenType: "web",
//		PStoreId:  req.PStoreId,
//		Id:        req.Id,
//	}
//	targetReq.Regions = make([]*inventory.CityExpressRegion, len(req.Regions))
//	for i, region := range req.Regions {
//		targetReq.Regions[i] = &inventory.CityExpressRegion{
//			StartingFee: region.StartingFee,
//			ShippingFee: region.ShippingFee,
//			Coordinates: util.ParseRawMessageToString(region.Coordinates),
//			CityCode:    region.CityCode,
//		}
//	}
//	if targetBody, err := json.Marshal(targetReq); err != nil {
//		// 重置请求body
//		r.Body = ioutil.NopCloser(&buf)
//	} else {
//		r.Body = ioutil.NopCloser(bytes.NewBuffer(targetBody))
//	}
//	return
//}
